package com.ailanyin.admin.modules.system.service.impl;

import com.ailanyin.admin.modules.system.service.SysFileService;
import com.ailanyin.common.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2022/2/28 0028 上午 9:42
 */
@Service
public class SysFileServiceImpl implements SysFileService {

    @Autowired
    private HttpServletRequest request;

    @Value("${ailanyin.uploadPath}")
    private String path;

    /**
     * 文件上传
     *
     * @param file file
     * @return url
     */
    @Override
    public String fileUpload(MultipartFile file) {
        return FileUtil.upload(file, request, path);
    }

    @Override
    public void fileDownload(String fileName, HttpServletResponse response) throws Exception{
        String realFileName = fileName.substring(fileName.indexOf("_") + 1);
        String filePath = FileUtil.getDownloadPath() + fileName;
        FileUtil.setAttachmentResponseHeader(response, realFileName);
        FileUtil.writeBytes(filePath, response.getOutputStream());
        FileUtil.deleteFile(filePath);
    }
}
